package com.sxj.shop.service.impl;

import com.sxj.shop.dao.ItemDao;
import com.sxj.shop.dao.OrderDao;
import com.sxj.shop.entity.Item;
import com.sxj.shop.entity.Order;
import com.sxj.shop.entity.User;
import com.sxj.shop.exception.RequestParameterErrorException;
import com.sxj.shop.exception.UserNotLoginException;
import com.sxj.shop.factory.ObjectFactory;
import com.sxj.shop.service.OrderService;
import com.sxj.shop.util.ParameterUtil;
import com.sxj.shop.vo.Cart;

import java.util.List;

public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = (OrderDao) ObjectFactory.getObject("orderDao");
    private ItemDao itemDao = (ItemDao) ObjectFactory.getObject("itemDao");

    @Override
    public String createNo(Cart cart, User user) throws UserNotLoginException {
        if (cart == null || user == null) {
            throw new UserNotLoginException("请先登录");
        }

        // 结算时同时保存订单与明细的信息,涉及一个订单与多个明细
        // 且明细属于当前保存的订单
        // 使用多表保存的方式进行实现
        // 1.先保存订单
        Order order = new Order();
        order.setNo(ParameterUtil.createNo());
        order.setPrice(cart.getPrice());
        order.setUser(user);
        // 调用dao方法保存订单并返回主键
        Integer id = orderDao.insertReturnPrimaryKey(order);
        // 获取到自动生成的主键的值之后,将主键的值赋值给对应的订单对象
        order.setId(id);

        // 2.后保存明细
        // 取出购物车中所有的明细
        List<Item> items = cart.getItems();
        // 遍历这些明细
        for (Item item : items) {
            // 需要将返回的订单号赋值给对应明细
            item.setOrder(order);
            // 每遍历一条明细,保存一条记录
            itemDao.insertItem(item);
        }

        return order.getNo();
    }

    @Override
    public List<Order> findMyOrders(User user) throws UserNotLoginException {
        if (user == null) {
            throw new UserNotLoginException("请先登录");
        }
        return orderDao.selectByUserId(user.getId());
    }

    @Override
    public Order findDetailById(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        return orderDao.selectDetailById(Integer.parseInt(id));
    }
}
